package io.kiki.sba.registry.server.clientInterface.acceptor;

import io.kiki.sba.registry.common.model.ClientToClientInterfaceServerNodeId;
import io.kiki.sba.registry.server.clientInterface.node.service.DataStoreNodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class WriteDataProcessor {

    private static final Logger logger = LoggerFactory.getLogger(WriteDataProcessor.class);

    private final ClientToClientInterfaceServerNodeId clientToClientInterfaceServerNodeId;

    private final DataStoreNodeService dataStoreNodeService;

    public WriteDataProcessor(DataStoreNodeService dataStoreNodeService, ClientToClientInterfaceServerNodeId clientToClientInterfaceServerNodeId) {
        this.clientToClientInterfaceServerNodeId = clientToClientInterfaceServerNodeId;
        this.dataStoreNodeService = dataStoreNodeService;
    }

    public boolean process(WriteDataRequest request) {
        switch (request.getWriteDataRequestType()) {
        case publisher:
            doPublishAsync(request);
            return true;
        case un_publisher:
            doUnPublishAsync(request);
            return true;
        case client_off:
            doClientOffAsync(request);
            return true;
        default:
            logger.error("Unknown request type, connectId={}, requestType={}, requestBody={}", clientToClientInterfaceServerNodeId, request.getWriteDataRequestType(), request.getClientOffPublishers());
        }
        return false;
    }


    private void doPublishAsync(WriteDataRequest request) {
        PublisherWriteDataRequest request1 = (PublisherWriteDataRequest) request;
        dataStoreNodeService.register(request1.getClientOffPublishers());
    }

    private void doUnPublishAsync(WriteDataRequest request) {
        PublisherWriteDataRequest request1 = (PublisherWriteDataRequest) request;
        dataStoreNodeService.unregister(request1.getClientOffPublishers());
    }

    private void doClientOffAsync(WriteDataRequest request) {
        ClientOffWriteDataRequest request1 = (ClientOffWriteDataRequest) request;
        dataStoreNodeService.clientOff(request1.getClientOffPublishers());
    }

}
